<?php

// $Id$

require_once(TANGRA_MAIN_DIR.'web_site/web_page/just_headers_view.class.php');


require_once($WSC->get_site_inc_dir().'modules/admin_panel/site_admin_ajax_form_ctrl_with_object_ua.class.php');
require_once($WSC->get_site_inc_dir().'modules/tangra_cms/forms/vpage/vpage_form_ctrl.class.php');
require_once($WSC->get_site_inc_dir().'modules/tangra_cms/classes/vpage/tcms_vpage_template_dbc.class.php');


class VPage_Form_Ajax_Ctrl extends Site_Admin_Ajax_Form_Ctrl_With_Object_UA {
	protected function init_transit_vars() {
		$this->add_transit_var('category');
		$this->add_transit_var('return_to');
	}


	protected function on_good_submit() {
		$object = $this->form_ctrl->get_object();

		$return_to = $this->get_transit_var('return_to');
		if ($return_to) {
			$redir = $this->create_redirect_composer($return_to, array('manage' => $object->get_id()));
		} else {
			$dbc = $this->get_dbc();
			$vp_template = new TCMS_VPage_Template_DBC();
			if ($vp_template->load_by_id($dbc, $object->get_template())) {
				if ($vp_template->get_man_path()) {
					$redir_view = $this->create_redirect_composer($vp_template->get_man_path(), array('manage' => $object->get_id()));
				} else {
					$redir_view = $this->create_redirect_composer($this->get_redir_on_success(), array('manage' => $object->get_id()));
				}
			} else {
				throw new Tangra_Module_Exception('Cannot load vpage template with ID = '.$object->get_template());
			}
		}

		$location = $redir->get_target_address($this->get__context());

		$ret = array('command' => Ajax_Ctrl::COMMAND_REDIRECT, 'command_value' => $location);

		return $ret;
	}


	protected function on_bad_submit() {
		$add_new = $this->form_ctrl->get_permanent_external_param('add_new', true);

		if ($add_new) {
			$this->export('add_new', 1);
		} else {
			$object = $this->form_ctrl->get_object();
			$this->export('vpage_id', $object->get_id());
		}

		$category_id = $this->get_transit_var('category', true);
		if ($category_id) {
			$this->export('category_id', $category_id);
		}


		return true;
	}


	protected function create_form_ctrl() {
		$tvm = $this->get_tvm();
		$dbc = $this->get_dbc();

		$config = $this->get__config();

		$ret = new vpage_Form_Ctrl('vpage', $tvm, $dbc, 'obj_id', $config->get_htdocs_dir(), $config->get_hidden_dir().'inc/');

		return $ret;
	}

}